/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.exporters;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * This class is a base for a manager that stores references. Each reference file format is as follows:
 * <pre>
 *             +--------+
 *     line 0  | HEADER | 
 *     line 1  | REF 1  |
 *     line 2  | REF 2  |
 *              .  .  .
 *     line N  | REF N  |
 *             +--------+
 * </pre> 
 *
 * @author Basil Shikin
 *
 */
public abstract class ReferenceStorage<T>
{
    protected final String name;
    
    private List<T> objects = new ArrayList<T>();
    
    
    /**
     * Create new reference manager
     * 
     * @param name Storage name. Will be used to save storage
     */ 
    protected ReferenceStorage( String name )
    {
        if ( name == null ) throw new IllegalArgumentException("Invalid name specified");
        
        this.name = name;
        
        objects.add( null ); // Add a null record into first location (so that objects[0] = null)
    }

    /**
     * Get object for a given reference ID
     * 
     * @param refID ID of the reference to get object for. Must be greater then zero.
     * 
     * @return Reference for given ID.
     * 
     * @throws IllegalArgumentException In case unknown reference ID specified
     */
    public T resolveObject( final short refID )
    {
        if ( refID < 0 || refID >= objects.size() ) throw new IllegalArgumentException("Invalid reference ID: " + refID );
        
        return objects.get( refID );
    }
    
    /**
     * Get reference ID for given object. Create a new reference ID in case no matching objects found
     * 
     * @param object Object to return id for. Must not be null.
     * 
     * @return ID of the reference.
     */
    public short getReferenceId( final T object )
    {
        if ( object == null ) throw new IllegalArgumentException("Invalid object specified"); 
        
        int result = objects.indexOf( object );
        if ( result < 0 )
        {
            objects.add( object );
            result = objects.size() - 1;
        }
        
        if ( result > Short.MAX_VALUE ) throw new RuntimeException("Too many references: " + result + " is greater then " + Short.MAX_VALUE );
        
        return (short)result;
    }
    
    /**
     * Add object to the storage.
     * 
     * @param object Object to add. Must not be null.
     * 
     * @return ID of newly added object
     */
    public short addObject( final T object )
    {
        return getReferenceId( object );
    }
    
    public String getName()
    {
        return name;
    }

    /**
     * Load all references/objects from reference file.
     * 
     * @param referenceFile File to load references from. Must not be null.
     * 
     * @throws IOException In case unable to write to references file.
     */
    public void loadReferences( final File referenceFile ) throws IOException
    {
        if ( referenceFile == null ) throw new IllegalArgumentException("Invalid reference file specified");
        if ( !referenceFile.exists() ) throw new IllegalArgumentException("Reference file does not exist");
        
        FileInputStream fis = null;
        BufferedReader  reader = null;
        try
        {
            fis = new FileInputStream( referenceFile );
            reader = new BufferedReader( new InputStreamReader( fis ) );
            
            reader.readLine(); // Ignore header for now
            
            String reference = reader.readLine();
            while ( reference != null )
            {
                objects.add( toObject( reference ) );
                
                reference = reader.readLine();
            }
        }
        finally
        {
            if ( fis != null)    fis.close();
            if ( reader != null) reader.close();
        }
    }
    
    /**
     * Write all references to reference file.
     * 
     * @param referenceFile File to store references in. Must not be null.
     *  
     * @throws IOException In case unable to write references.
     */
    public void saveReferences( final File referenceFile  ) throws IOException
    {
        if ( referenceFile == null ) throw new IllegalArgumentException("Invalid reference file specified");
        
        
        if ( !referenceFile.exists() ) referenceFile.createNewFile();
        
        FileOutputStream fos = null;
        BufferedWriter   writer = null;
        try
        {
            fos = new FileOutputStream( referenceFile, false ); // Overwrite file (do not append)
            writer = new BufferedWriter( new OutputStreamWriter( fos ) );
            
            writer.write( "\n" ); // Write empty header
            
            for ( T reference : objects )
            {
                if ( reference != null )
                {
                    writer.write( toString( reference )  );
                    writer.write('\n');
                }
            }
            
            writer.flush();
        }
        finally
        {
            if ( writer != null) writer.close();
            if ( fos != null)    fos.close();
        }
    }
    
    /**
     * Serialize object into a string.
     * 
     * @param object Object to serialize. Guaranteed not to be null.
     * 
     * @return Serialized string. Must not be null.
     */
    protected abstract String toString( final T object );
    
    /**
     * Un-serialize object from a string.
     * 
     * @param objectString Serialized string. Guaranteed not to be null.
     * 
     * @return Un-serialized object. Must not be null. 
     */
    protected abstract T toObject( final String objectString);
}
